from decimal import Decimal

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from .serializers import CartSKUSerializer, PlaceOrderSerialzier

# Create your views here.
from goods.models import SKU


class PlaceOrderView(APIView):
    """

        获取订单相关的数据
        1.必须是登录用户才可以访问的
        2.商品列表的数据都是通过redis获取，而且是获取的 选中商品的信息
        3.把运费动态返回给前段

        GET      /orders/places/
        """


    permission_classes = [IsAuthenticated]

    def get(self, request):

        # 2.获取用户信息
        user = request.user

        # 3.连接redis
        redis_conn = get_redis_connection('cart')
        # 4.hash
        redis_id_count = redis_conn.hgetall('cart_%s' % user.id)
        # {b'sku_id':b'count'}
        # 5.set数据
        redis_selected_ids = redis_conn.smembers('cart_selected_%s' % user.id)
        # {b'1'}


        # 6.获取的选中商品的信息
        selected_data = {}
        # 对选中的id进行遍历
        for sku_id in redis_selected_ids:
            selected_data[int(sku_id)] = int(redis_id_count[sku_id])

        # [sku_id,sku_id,sku_id]
        # 【SKU,SKU,SKU】
        skus = SKU.objects.filter(pk__in=selected_data.keys())

        for sku in skus:
            sku.count = selected_data[sku.id]

            # 7.将对象列表转换为字典
            # serializer = CartSKUSerializer(skus,many=True)
            # 8. 需要返回运费

            """
            {
                'skus': [],
                'freight':'10.00'
            }
            """
        freight = Decimal('10.00')

        # Decimal 是一个货币类型
        # 1.23
        # 0.23 是以无限接近于真实值形式存在

        # 100 / 3 = 33.33   33.33*3 =99.99
        #       33.33   33.33   33.34
        # Decimal 不会造成精度的丢失


        serializer = PlaceOrderSerialzier({'skus': skus,
                                           'freight': freight})

        return Response(serializer.data)
